package com.example.demotest.controller;

import com.example.demotest.pojo.ChatMessage;
import com.example.demotest.pojo.User;
import com.example.demotest.pojo.dto.ChatMessageDto;
import com.example.demotest.repository.ChatMessageRepository;
import com.example.demotest.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/user/chat")
public class ChatMessageController {

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Autowired
    private UserRepository userRepository;

    // 发送消息
    @PostMapping("/send")
    public ResponseEntity<?> sendMessage(@RequestBody ChatMessageDto messageDto) {
        Optional<User> senderOpt = userRepository.findById(messageDto.getSenderId());
        Optional<User> receiverOpt = userRepository.findById(messageDto.getReceiverId());

        if (senderOpt.isEmpty() || receiverOpt.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户不存在");
        }

        ChatMessage message = new ChatMessage();
        message.setSender(senderOpt.get());
        message.setReceiver(receiverOpt.get());
        message.setContent(messageDto.getContent());
        message.setTimestamp(LocalDateTime.now());
        message.setRead(false);

        chatMessageRepository.save(message);
        return ResponseEntity.ok("发送成功");
    }

    // 获取聊天记录
    @GetMapping("/history")
    public ResponseEntity<?> getChatHistory(@RequestParam Integer user1, @RequestParam Integer user2) {
        Optional<User> u1 = userRepository.findById(user1);
        Optional<User> u2 = userRepository.findById(user2);

        if (u1.isEmpty() || u2.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户不存在");
        }

        List<ChatMessage> messages = chatMessageRepository.findBySenderAndReceiverOrderByTimestampAsc(u1.get(), u2.get());
        messages.addAll(chatMessageRepository.findBySenderAndReceiverOrderByTimestampAsc(u2.get(), u1.get()));
        messages.sort(Comparator.comparing(ChatMessage::getTimestamp));

        return ResponseEntity.ok(messages);
    }
}